﻿<?php

/* 根据用户UID获得用户头像地址 */

function get_avatar_dir($uid) {
    global $setting;
    if ($setting['ucenter_open']) {
        return $setting['ucenter_url'] . '/avatar.php?uid=' . $uid . '&size=middle';
    } else {
        $uid = sprintf("%09d", $uid);
        $dir1 = substr($uid, 0, 3);
        $dir2 = substr($uid, 3, 2);
        $dir3 = substr($uid, 5, 2);
        $avatar_dir = "data/avatar/" . $dir1 . '/' . $dir2 . '/' . $dir3 . "/small_" . $uid;

        if (file_exists($avatar_dir . ".jpg"))
            return SITE_URL . $avatar_dir . ".jpg";
        if (file_exists($avatar_dir . ".jepg"))
            return SITE_URL . $avatar_dir . ".jepg";
        if (file_exists($avatar_dir . ".gif"))
            return SITE_URL . $avatar_dir . ".gif";
        if (file_exists($avatar_dir . ".png"))
            return SITE_URL . $avatar_dir . ".png";
    }
//显示系统默认头像
    return SITE_URL . 'css/default/avatar.gif';
}

/* 伪静态和html纯静态可以同时存在 */

function url($var, $url='') {
    global $setting;
    $location = '?' . $var . $setting['seo_suffix'];
    if ($setting['seo_on']) {
        $rewritearray = array('question/view/', 'category/view/', 'category/list/', 'category/recommend/', 'user/space/', 'user/scorelist/');
        foreach ($rewritearray as $item) {
            if (false !== strpos($var, $item)) {
                $location = $var . $setting['seo_suffix'];
            }
        }
    }
    $location = urlmap($location, 2);
    if ($url)
        return SITE_URL . $location; //程序动态获取的，给question的model使用
    else
        return '<?=SITE_URL?>' . $location; //模板编译时候生成使用
}

/* url转换器，1为请求转换，就是把类似q-替换为question/view
  2为反向转换，就是把类似/question/view/替换为q-
 */

function urlmap($var, $direction=1) {
    $replaces = array(
        'q-' => 'question/view/',
        'c-' => 'category/view/',
        'l-' => 'category/list/',
        'r-' => 'category/recommend/',
        'u-' => 'user/space/',
        'us-' => 'user/scorelist/',
    );
    (2 == $direction) && $replaces = array_flip($replaces);
    return str_replace(array_keys($replaces), array_values($replaces), $var);
}

/**
 * random
 * @param int $length
 * @return string $hash
 */
function random($length=6, $type=0) {
    $hash = '';
    $chararr = array(
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz',
        '0123456789',
        '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'
    );
    $chars = $chararr[$type];
    $max = strlen($chars) - 1;
    PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000);
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function cutstr($string, $length, $dot = ' ...') {
    if (strlen($string) <= $length) {
        return $string;
    }
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
    $strcut = '';
    if (strtolower(TIPASK_CHARSET) == 'utf-8') {
        $n = $tn = $noc = 0;
        while ($n < strlen($string)) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length) {
                break;
            }
        }
        if ($noc > $length) {
            $n -= $tn;
        }
        $strcut = substr($string, 0, $n);
    } else {
        for ($i = 0; $i < $length; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
        }
    }
    $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
    return $strcut . $dot;
}

function generate_key() {
    $random = random(20);
    $info = md5($_SERVER['SERVER_SOFTWARE'] . $_SERVER['SERVER_NAME'] . $_SERVER['SERVER_ADDR'] . $_SERVER['SERVER_PORT'] . $_SERVER['HTTP_USER_AGENT'] . time());
    $return = '';
    for ($i = 0; $i < 64; $i++) {
        $p = intval($i / 2);
        $return[$i] = $i % 2 ? $random[$p] : $info[$p];
    }
    return implode('', $return);
}

/**
 * getip
 * @return string
 */
function getip() {
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } else if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    preg_match("/[\d\.]{7,15}/", $ip, $temp);
    $ip = $temp[0] ? $temp[0] : 'unknown';
    unset($temp);
    return $ip;
}

//格式化前端IP显示
function formatip($ip, $type=1) {
    if (strtolower($ip) == 'unknown') {
        return false;
    }
    if ($type == 1) {
        $ipaddr = substr($ip, 0, strrpos($ip, ".")) . ".*";
    }
    return $ipaddr;
}

function forcemkdir($path) {
    if (!file_exists($path)) {
        forcemkdir(dirname($path));
        mkdir($path, 0777);
    }
}

function cleardir($dir, $forceclear=false) {
    if (!is_dir($dir)) {
        return;
    }
    $directory = dir($dir);
    while ($entry = $directory->read()) {
        $filename = $dir . '/' . $entry;
        if (is_file($filename)) {
            @unlink($filename);
        } elseif (is_dir($filename) && $forceclear && $entry != '.' && $entry != '..') {
            chmod($filename, 0777);
            cleardir($filename, $forceclear);
            rmdir($filename);
        }
    }
    $directory->close();
}

function iswriteable($file) {
    $writeable = 0;
    if (is_dir($file)) {
        $dir = $file;
        if ($fp = @fopen("$dir/test.txt", 'w')) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = 1;
        }
    } else {
        if ($fp = @fopen($file, 'a+')) {
            @fclose($fp);
            $writeable = 1;
        }
    }
    return $writeable;
}

function readfromfile($filename) {    
    if ($fp = @fopen($filename, 'rb')) {
        if (PHP_VERSION >= '4.3.0' && function_exists('file_get_contents')) {
            return file_get_contents($filename);
        } else {
            flock($fp, LOCK_EX);
            $data = fread($fp, filesize($filename));
            flock($fp, LOCK_UN);
            fclose($fp);
            return $data;
        }
    } else {
        return '';
    }
}

function readfromfileme($filename) {    
    //首先要判断给定的文件存在与否
    if(!file_exists($filename)){
         echo "没有该文件文件";
      return '';
    }
    bomtoutf8($filename);
    if ($fp = @fopen($filename, 'rb')) {
        if (PHP_VERSION >= '4.3.0' && function_exists('file_get_contents')) {
            return file_get_contents($filename);
        } else {
            flock($fp, LOCK_EX);
            $data = fread($fp, filesize($filename));
            flock($fp, LOCK_UN);
            fclose($fp);
            return $data;
        }
    } else {
        return '';
    }
}

function bomtoutf8($filename)  
{  
    $ef = 239;  
    $bb = 187;  
    $bf = 191;  
  
    if (is_dir($filename)) return;  
    $fd = fopen($filename, "rb");  
    if (!$fd) exit($filename);  
    $headers = fread($fd, 3);  
    fclose($fd);  
      
    if (strlen($headers) < 3) return;  
  
    if (ord($headers[0]) == $ef &&   
        ord($headers[1]) == $bb &&  
        ord($headers[2]) == $bf  
        ) {  
        echo $filename, "\n";  
        $content = file_get_contents($filename);  
        if (!$content) {  
            exit("");  
        }  
        $len = strlen($content);  
        $content = substr($content, 3);  
  
        if ($content === false && $len!=3) {  
            exit("");  
        } else if ($content === false && $len==3){  
            $content = "";  
        }  
        $ret = file_put_contents($filename, $content, LOCK_EX);  
        if ($ret === false) {  
            exit("");  
        }
    }
}  

function rewrite ($filename, $data) {
   $filenum=fopen($filename,"w");
   flock($filenum,LOCK_EX);
   fwrite($filenum,$data);
   fclose($filenum);
}

function writetofile($filename, &$data) {
    if ($fp = @fopen($filename, 'wb')) {
        if (PHP_VERSION >= '4.3.0' && function_exists('file_put_contents')) {
            return @file_put_contents($filename, $data);
        } else {
            flock($fp, LOCK_EX);
            $bytes = fwrite($fp, $data);
            flock($fp, LOCK_UN);
            fclose($fp);
            return $bytes;
        }
    } else {
        return 0;
    }
}

function extname($filename) {
    $pathinfo = pathinfo($filename);
    return strtolower($pathinfo['extension']);
}

function taddslashes($string, $force = 0) {
    if (!MAGIC_QUOTES_GPC || $force) {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $string[$key] = taddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}

/* XSS 检测 */

function checkattack($reqarr, $reqtype='post') {
    $filtertable = array(
        'get' => '\'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)',
        'post' => '\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)',
        'cookie' => '\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)'
    );
    foreach ($reqarr as $reqkey => $reqvalue) {
        if (preg_match("/" . $filtertable[$reqtype] . "/is", $reqvalue) == 1) {
            print('Illegal operation!');
            exit(-1);
        }
    }
}

function tstripslashes($string) {
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = tstripslashes($val);
        }
    } else {
        $string = stripslashes($string);
    }
    return $string;
}

function template($file, $tpldir = '') {
    global $setting;
    $tpldir = ('' == $tpldir) ? $setting['tpl_dir'] : $tpldir;
    $tplfile = TIPASK_ROOT . '/view/' . $tpldir . '/' . $file . '.html';
    $objfile = TIPASK_ROOT . '/data/view/' . $tpldir . '_' . $file . '.tpl.php';
    if ('default' != $tpldir && !is_file($tplfile)) {
        $tplfile = TIPASK_ROOT . '/view/default/' . $file . '.html';
        $objfile = TIPASK_ROOT . '/data/view/default_' . $file . '.tpl.php';
    }
    if (!file_exists($objfile) || (@filemtime($tplfile) > @filemtime($objfile))) {
        require_once TIPASK_ROOT . '/lib/template.func.php';
        parse_template($tplfile, $objfile);
    }
    return $objfile;
}

function timeLength($time) {
    $length = '';
    if ($day = floor($time / (24 * 3600))) {
        $length .= $day . '天';
    }
    if ($hour = floor($time % (24 * 3600) / 3600)) {
        $length .= $hour . '小时';
    }
    if ($day == 0 && $hour == 0) {
        $length = floor($time / 60) . '分钟';
    }
    return $length;
}

/* 验证码生成 */

function makecode($code) {
    $codelen = strlen($code);
    $im = imagecreate(50, 20);
    $font_type = TIPASK_ROOT . '/css/common/ninab.ttf';
    $bgcolor = ImageColorAllocate($im, 245, 245, 245);
    $iborder = ImageColorAllocate($im, 0x71, 0x76, 0x67);
    $fontColor = ImageColorAllocate($im, 0x50, 0x4d, 0x47);
    $fontColor2 = ImageColorAllocate($im, 0x36, 0x38, 0x32);
    $fontColor1 = ImageColorAllocate($im, 0xbd, 0xc0, 0xb8);
    $lineColor1 = ImageColorAllocate($im, 130, 220, 245);
    $lineColor2 = ImageColorAllocate($im, 225, 245, 255);
    for ($j = 3; $j <= 16; $j = $j + 3)
        imageline($im, 2, $j, 48, $j, $lineColor1);
    for ($j = 2; $j < 52; $j = $j + (mt_rand(3, 6)))
        imageline($im, $j, 2, $j - 6, 18, $lineColor2);
    imagerectangle($im, 0, 0, 49, 19, $iborder);
    $strposs = array();
    for ($i = 0; $i < $codelen; $i++) {
        if (function_exists("imagettftext")) {
            $strposs[$i][0] = $i * 10 + 6;
            $strposs[$i][1] = mt_rand(15, 18);
            imagettftext($im, 11, 5, $strposs[$i][0] + 1, $strposs[$i][1] + 1, $fontColor1, $font_type, $code[$i]);
        } else {
            imagestring($im, 5, $i * 10 + 6, mt_rand(2, 4), $code[$i], $fontColor);
        }
    }
    for ($i = 0; $i < $codelen; $i++) {
        if (function_exists("imagettftext")) {
            imagettftext($im, 11, 5, $strposs[$i][0] - 1, $strposs[$i][1] - 1, $fontColor2, $font_type, $code[$i]);
        }
    }
    header("Pragma:no-cache\r\n");
    header("Cache-Control:no-cache\r\n");
    header("Expires:0\r\n");
    if (function_exists("imagejpeg")) {
        header("content-type:image/jpeg\r\n");
        imagejpeg($im);
    } else {
        header("content-type:image/png\r\n");
        imagepng($im);
    }
    ImageDestroy($im);
}

/* 通用加密解密函数，phpwind、phpcms、dedecms都用此函数 */

function strcode($string, $auth_key, $action='ENCODE') {
    $key = substr(md5($_SERVER["HTTP_USER_AGENT"] . $auth_key), 8, 18);
    $string = $action == 'ENCODE' ? $string : base64_decode($string);
    $len = strlen($key);
    $code = '';
    for ($i = 0; $i < strlen($string); $i++) {
        $k = $i % $len;
        $code .= $string[$i] ^ $key[$k];
    }
    $code = $action == 'DECODE' ? $code : base64_encode($code);
    return $code;
}

// 参数解释   
// $string： 明文 或 密文   
// $operation：DECODE表示解密,其它表示加密   
// $key： 密匙   
// $expiry：密文有效期   
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {   
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙   
    $ckey_length = 4;   
       
    // 密匙   
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);   
       
    // 密匙a会参与加解密   
    $keya = md5(substr($key, 0, 16));   
    // 密匙b会用来做数据完整性验证   
    $keyb = md5(substr($key, 16, 16));   
    // 密匙c用于变化生成的密文   
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';   
    // 参与运算的密匙   
    $cryptkey = $keya.md5($keya.$keyc);   
    $key_length = strlen($cryptkey);   
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性   
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确   
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;   
    $string_length = strlen($string);   
    $result = '';   
    $box = range(0, 255);   
    $rndkey = array();   
    // 产生密匙簿   
    for($i = 0; $i <= 255; $i++) {   
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);   
     }   
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度   
    for($j = $i = 0; $i < 256; $i++) {   
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;   
        $tmp = $box[$i];   
        $box[$i] = $box[$j];   
        $box[$j] = $tmp;   
     }   
    // 核心加解密部分   
    for($a = $j = $i = 0; $i < $string_length; $i++) {   
        $a = ($a + 1) % 256;   
        $j = ($j + $box[$a]) % 256;   
        $tmp = $box[$a];   
        $box[$a] = $box[$j];   
        $box[$j] = $tmp;   
        // 从密匙簿得出密匙进行异或，再转成字符   
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));   
     }   
    if($operation == 'DECODE') {   
        // substr($result, 0, 10) == 0 验证数据有效性   
        // substr($result, 0, 10) - time() > 0 验证数据有效性   
        // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性   
        // 验证数据有效性，请看未加密明文的格式   
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {   
            return substr($result, 26);   
         } else {   
            return '';   
         }   
     } else {   
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因   
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码   
        return $keyc.str_replace('=', '', base64_encode($result));   
     }   
}

/* 日期格式显示 */

function tdate($time, $type = 3, $friendly=1) {
    global $setting;
    ($setting['time_friendly'] != 1) && $friendly = 0;
    $format[] = $type & 2 ? (!empty($setting['date_format']) ? $setting['date_format'] : 'Y-n-j') : '';
    $format[] = $type & 1 ? (!empty($setting['time_format']) ? $setting['time_format'] : 'H:i') : '';
    $timeoffset = $setting['time_offset'] * 3600 + $setting['time_diff'] * 60;
    $timestring = gmdate(implode(' ', $format), $time + $timeoffset);
    if ($friendly) {
        $time = time() - $time;
        if ($time <= 24 * 3600) {
            if ($time > 3600) {
                $timestring = intval($time / 3600) . '小时前';
            } elseif ($time > 60) {
                $timestring = intval($time / 60) . '分钟前';
            } elseif ($time > 0) {
                $timestring = $time . '秒前';
            } else {
                $timestring = '现在前';
            }
        }
    }
    return $timestring;
}

/* cookie设置和读取 */

function tcookie($var, $value=0, $life = 0) {
    global $setting;
    $cookiepre = $setting['cookie_pre'] ? $setting['cookie_pre'] : 't_';
    if (0 === $value) {
        return isset($_COOKIE[$cookiepre . $var]) ? $_COOKIE[$cookiepre . $var] : '';
    } else {
        if (0 === $life) {
		setcookie($cookiepre . $var, $value);
        } else {
        	$domain = $setting['cookie_domain'] ? $setting['cookie_domain'] : '';
        	setcookie($cookiepre . $var, $value, $life ? time() + $life : 0, '/', $domain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
        }
    }
}

/* 日志记录 */

function runlog($file, $message, $halt=0) {
    $nowurl = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
    $log = tdate($_SERVER['REQUEST_TIME'], 'Y-m-d H:i:s') . "\t" . $_SERVER['REMOTE_ADDR'] . "\t{$nowurl}\t" . str_replace(array("\r", "\n"), array(' ', ' '), trim($message)) . "\n";
    $yearmonth = gmdate('Ym', $_SERVER['REQUEST_TIME']);
    $logdir = TIPASK_ROOT . '/data/logs/';
    if (!is_dir($logdir))
        mkdir($logdir, 0777);
    $logfile = $logdir . $yearmonth . '_' . $file . '.php';
    if (@filesize($logfile) > 2048000) {
        $dir = opendir($logdir);
        $length = strlen($file);
        $maxid = $id = 0;
        while ($entry = readdir($dir)) {
            if (strexists($entry, $yearmonth . '_' . $file)) {
                $id = intval(substr($entry, $length + 8, -4));
                $id > $maxid && $maxid = $id;
            }
        }
        closedir($dir);
        $logfilebak = $logdir . $yearmonth . '_' . $file . '_' . ($maxid + 1) . '.php';
        @rename($logfile, $logfilebak);
    }
    if ($fp = @fopen($logfile, 'a')) {
        @flock($fp, 2);
        fwrite($fp, "<?PHP exit;?>\t" . str_replace(array('<?', '?>', "\r", "\n"), '', $log) . "\n");
        fclose($fp);
    }
    if ($halt)
        exit();
}

/* 翻页函数 */

function page($num, $perpage, $curpage, $operation) {
    global $setting;
    $multipage = '';
    $operation = urlmap($operation, 2);

    $mpurl = SITE_URL . $setting['seo_prefix'] . $operation . '/';
    ('admin' == substr($operation, 0, 5)) && ( $mpurl = 'index.php?' . $operation . '/');

    if ($num > $perpage) {
        $page = 10;
        $offset = 2;
        $pages = @ceil($num / $perpage);
        if ($page > $pages) {
            $from = 1;
            $to = $pages;
        } else {
            $from = $curpage - $offset;
            $to = $from + $page - 1;
            if ($from < 1) {
                $to = $curpage + 1 - $from;
                $from = 1;
                if ($to - $from < $page) {
                    $to = $page;
                }
            } elseif ($to > $pages) {
                $from = $pages - $page + 1;
                $to = $pages;
            }
        }
        $multipage = ($curpage - $offset > 1 && $pages > $page ? '<a  class="n" href="' . $mpurl . '1' . $setting['seo_suffix'] . '" >首页</a>' . "\n" : '') .
                ($curpage > 1 ? '<a href="' . $mpurl . ($curpage - 1) . $setting['seo_suffix'] . '"  class="n">上一页</a>' . "\n" : '');
        for ($i = $from; $i <= $to; $i++) {
            $multipage .= $i == $curpage ? "<strong>$i</strong>\n" :
                    '<a href="' . $mpurl . $i . $setting['seo_suffix'] . '">' . $i . '</a>' . "\n";
        }
        $multipage .= ( $curpage < $pages ? '<a class="n" href="' . $mpurl . ($curpage + 1) . $setting['seo_suffix'] . '">下一页</a>' . "\n" : '') .
                ($to < $pages ? '<a class="n" href="' . $mpurl . $pages . $setting['seo_suffix'] . '" >最后一页</a>' . "\n" : '');
    }
    return $multipage;
}

/* 过滤关键词 */

function checkwords($content) {
    global $setting, $badword;
    $status = 0;
    $text = $content;
    if (!empty($badword)) {
        foreach ($badword as $word => $wordarray) {
            $replace = $wordarray['replacement'];
            $content = str_replace($word, $replace, $content, $matches);
            if ($matches > 0) {
                '{MOD}' == $replace && $status = 1;
                '{BANNED}' == $replace && $status = 2;
                if ($status > 0) {
                    $content = $text;
                    break;
                }
            }
        }
    }
//$content = str_replace(array("\r\n", "\r", "\n"), '<br />', htmlentities($content));
    return array($status, $content);
}

/* 过滤number create3 */

function checkNumber($content) {
    for($i=0; $i < strlen($content); $i++)
    {
        if (intval(substr($content,$i,1))) {
           continue;
        }
        else {
           return 0;
           break;
        }
    }
    return 1;
}

/* http请求 */

function topen($url, $timeout = 15, $post = '', $cookie = '', $limit = 0, $ip = '', $block = TRUE) {
    $return = '';
    $matches = parse_url($url);
    $host = $matches['host'];
    $path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
    $port = !empty($matches['port']) ? $matches['port'] : 80;
    if ($post) {
        $out = "POST $path HTTP/1.0\r\n";
        $out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
        $out .= "Accept-Language: zh-cn\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
        $out .= "Host: $host\r\n";
        $out .= 'Content-Length: ' . strlen($post) . "\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Cache-Control: no-cache\r\n";
        $out .= "Cookie: $cookie\r\n\r\n";
        $out .= $post;
    } else {
        $out = "GET $path HTTP/1.0\r\n";
        $out .= "Accept: */*\r\n";
//$out .= "Referer: $boardurl\r\n";
        $out .= "Accept-Language: zh-cn\r\n";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Cookie: $cookie\r\n\r\n";
    }
    $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
    if (!$fp) {
        return '';
    } else {
        stream_set_blocking($fp, $block);
        stream_set_timeout($fp, $timeout);
        @fwrite($fp, $out);
        $status = stream_get_meta_data($fp);
        if (!$status['timed_out']) {
            while (!feof($fp)) {
                if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
                    break;
                }
            }
            $stop = false;
            while (!feof($fp) && !$stop) {
                $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
                $return .= $data;
                if ($limit) {
                    $limit -= strlen($data);
                    $stop = $limit <= 0;
                }
            }
        }
        @fclose($fp);
        return $return;
    }
}
/* 发送邮件 免费企业邮箱简单发送*/
function sendmailNew($touser, $subject, $message, $from = '') {
    global $setting;    
    $toemail = $touser['email'];
    $tousername = $touser['username'];
    $message = <<<EOT
		hi, $tousername :<br>
                                $subject<br>
                    $message<br>
		-----------------------<br>
		这封邮件由系统自动发送，请不要回复。
EOT;
    
     $email_to = $toemail;   //email地址,多个地址用,分隔开
     $email_subject = $subject;//email标题
     $email_message = $message;//邮件内容
     $charset = 'UFT-8';//邮件编码
     $mailconf = array(
        'mailsend'=>'2',
        'mailserver'=>'smtp.qq.com',
        'mailport'=>'25',
        'mailauth'=>'1',
        'mailfrom'=>'admin@kuaiwd.com',
        'mailauth_username'=>'admin@kuaiwd.com',
        'mailauth_password'=>'qin1234',
        'maildelimiter'=>'0',
        'mailsilent'=>'0',
     );
   sharpng_sendmail($email_to, $email_subject, $email_message, $charset, $mailconf);    
}

/* 发送邮件 系统本身带的发送方法（默认）*/
function sendmail($touser, $subject, $message, $from = '') {
    global $setting;
    $toemail = $touser['email'];
    $tousername = $touser['username'];
    $message = <<<EOT
		<html>
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset={TIPASK_CHARSET}">
		<title>$subject</title>
		</head>
		<body>
		hi, $tousername<br>
            $subject<br>
            $message<br><br><br><br>
		这封邮件由系统自动发送，请不要回复。
		</body>
		</html>
EOT;

    $maildelimiter = $setting['maildelimiter'] == 1 ? "\r\n" : ($setting['maildelimiter'] == 2 ? "\r" : "\n");
    $mailusername = isset($setting['mailusername']) ? $setting['mailusername'] : 1;
    $mailserver = $setting['mailserver'];
    $mailport = $setting['mailport'] ? $setting['mailport'] : 25;
    $mailsend = $setting['mailsend'] ? $setting['mailsend'] : 1;

    if ($mailsend == 3) {
        $email_from = empty($from) ? $setting['maildefault'] : $from;
    } else {
        $email_from = $from == '' ? '=?' . TIPASK_CHARSET . '?B?' . base64_encode($setting['site_name']) . "?= <" . $setting['maildefault'] . ">" : (preg_match('/^(.+?) \<(.+?)\>$/', $from, $mats) ? '=?' . TIPASK_CHARSET . '?B?' . base64_encode($mats[1]) . "?= <$mats[2]>" : $from);
    }

    $email_to = preg_match('/^(.+?) \<(.+?)\>$/', $toemail, $mats) ? ($mailusername ? '=?' . CHARSET . '?B?' . base64_encode($mats[1]) . "?= <$mats[2]>" : $mats[2]) : $toemail;
    ;

    $email_subject = '=?' . TIPASK_CHARSET . '?B?' . base64_encode(preg_replace("/[\r|\n]/", '', '[' . $setting['site_name'] . '] ' . $subject)) . '?=';
    $email_message = chunk_split(base64_encode(str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $message))))));

    $headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Ask1.0 {$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=" . TIPASK_CHARSET . "{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";

    if ($mailsend == 1) {
        if (function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
            return true;
        }
        return false;
    } elseif ($mailsend == 2) {

        if (!$fp = fsockopen($mailserver, $mailport, $errno, $errstr, 30)) {
            runlog('SMTP', "($mailserver:$mailport) CONNECT - Unable to connect to the SMTP server", 0);
            return false;
        }
        stream_set_blocking($fp, true);

        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != '220') {
            runlog('SMTP', "($mailserver:$mailport) CONNECT - $lastmessage", 0);
            return false;
        }

        fputs($fp, ($setting['mailauth'] ? 'EHLO' : 'HELO') . " Tipask\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
            runlog('SMTP', "($mailserver:$mailport) HELO/EHLO - $lastmessage", 0);
            return false;
        }

        while (1) {
            if (substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
                break;
            }
            $lastmessage = fgets($fp, 512);
        }

        if ($setting['mailauth']) {
            fputs($fp, "AUTH LOGIN\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 334) {
                runlog('SMTP', "($mailserver:$mailport) AUTH LOGIN - $lastmessage", 0);
                return false;
            }

            fputs($fp, base64_encode($setting['mailauth_username']) . "\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 334) {
                runlog('SMTP', "($mailserver:$mailport) USERNAME - $lastmessage", 0);
                return false;
            }

            fputs($fp, base64_encode($setting['mailauth_password']) . "\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 235) {
                runlog('SMTP', "($mailserver:$mailport) PASSWORD - $lastmessage", 0);
                return false;
            }

            $email_from = $setting['maildefault'];
        }

        fputs($fp, "MAIL FROM: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from) . ">\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 250) {
            fputs($fp, "MAIL FROM: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from) . ">\r\n");
            $lastmessage = fgets($fp, 512);
            if (substr($lastmessage, 0, 3) != 250) {
                runlog('SMTP', "($mailserver:$mailport) MAIL FROM - $lastmessage", 0);
                return false;
            }
        }

        fputs($fp, "RCPT TO: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail) . ">\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 250) {
            fputs($fp, "RCPT TO: <" . preg_replace("/.*\<(.+?)\>.*/", "\\1", $toemail) . ">\r\n");
            $lastmessage = fgets($fp, 512);
            runlog('SMTP', "($mailserver:$mailport) RCPT TO - $lastmessage", 0);
            return false;
        }

        fputs($fp, "DATA\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 354) {
            runlog('SMTP', "($mailserver:$mailport) DATA - $lastmessage", 0);
            return false;
        }

        $headers .= 'Message-ID: <' . gmdate('YmdHs') . '.' . substr(md5($email_message . microtime()), 0, 6) . rand(100000, 999999) . '@' . $_SERVER['HTTP_HOST'] . ">{$maildelimiter}";

        fputs($fp, "Date: " . gmdate('r') . "\r\n");
        fputs($fp, "To: " . $email_to . "\r\n");
        fputs($fp, "Subject: " . $email_subject . "\r\n");
        fputs($fp, $headers . "\r\n");
        fputs($fp, "\r\n\r\n");
        fputs($fp, "$email_message\r\n.\r\n");
        $lastmessage = fgets($fp, 512);
        if (substr($lastmessage, 0, 3) != 250) {
            runlog('SMTP', "($mailserver:$mailport) END - $lastmessage", 0);
        }
        fputs($fp, "QUIT\r\n");

        return true;
    } elseif ($mailsend == 3) {

        ini_set('SMTP', $mailserver);
        ini_set('smtp_port', $mailport);
        ini_set('sendmail_from', $email_from);

        if (function_exists('mail') && @mail($email_to, $email_subject, $email_message, $headers)) {
            return true;
        }
        return false;
    }
}

function sharpng_sendmail($email_to, $email_subject, $email_message, $charset, $mailconf){
/**
* 必须参数
* ++++++++++++++++++++
* 收信人地址
* $email_to 例如sjf124@126.com
* 邮件标题
* $email_subject 例如 祝贺您称为sharpng的客户
* 邮件内容
* $email_message 例如 sharpng是最好的wap建站程序之一,在您的帮助下,sharpng将会更好的成长
* 发送方式(三选一)
* $mailsend=1 通过 PHP 函数的 sendmail 发送(推荐此方式)
* $mailsend=2 通过 SOCKET 连接 SMTP 服务器发送(支持 ESMTP 验证)
* $mailsend=3 通过 PHP 函数 SMTP 发送 Email(仅 Windows 主机下有效, 不支持 ESMTP 验证)
* 邮件头的分隔符,请根据您邮件服务器的设置调整此参数(三选一)
* $maildelimiter=0 使用 LF 作为分隔符(通常为 Unix/Linux 主机)
* $maildelimiter=1 使用 CRLF 作为分隔符(通常为 Windows 主机)
* $maildelimiter=2 使用 CR 作为分隔符(通常为 Mac 主机)
* 屏蔽邮件发送中的全部错误提示(二选一)
* $mailsilent=1 是
* $mailsilent=0否
* ++++++++++++++++++++
* 下面的 参数根据$mailsend参数的值选择性输入
* ----------
* 假如$mailsend=2/3
* $mailserver SMTP 服务器,例如smtp.126.com
* $mailport SMTP 端口 默认为 25,例如25
* ----------
* 假如$mailsend=2
* $mailauth=1 是/$mailauth=0 否 - 要求身份验证,如果 SMTP 服务器要求身份验证才可以发信，请选择“是”(二选一)
* $mailfrom 发信人邮件地址 如果需要验证, 必须为本服务器的邮件地址。邮件地址中如果要包含用户名，格式为“username <user@domain.com>”，也可以只填地址,例如 sjf124@126.com
* $mailauth_username SMTP 身份验证用户名，如126邮箱的是sjf124@126.com
* $mailauth_password SMTP 身份验证密码
* ----------
*/
while(list($k,$v) = each($mailconf)) {                
($k == 'mailsend') ? $mailsend = $v : '';
($k == 'mailserver') ? $mailserver = $v : '';
($k == 'mailport') ? $mailport = $v : '';
($k == 'mailauth') ? $mailauth = $v : '';
($k == 'mailfrom') ? $mailfrom = $v : '';
($k == 'mailauth_username') ? $mailauth_username = $v : '';
($k == 'mailauth_password') ? $mailauth_password = $v : '';
($k == 'maildelimiter') ? $maildelimiter = $v : '';
($k == 'mailsilent') ? $sendmail_silent = $v : '';
}
if($sendmail_silent) {
error_reporting(0);
}
//分隔符
$maildelimiter = !empty($maildelimiter) ? "\r\n" : "\n";

$email_subject = '=?'.$charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', $email_subject))).'?=';
$mailsite = strstr($email_to,'@');

if (in_array($mailsite,array('@gmail.com',))) {
$email_message = str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $email_message)))));
} else {
$email_message = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $email_message)))))));    
}

foreach(explode(',', $email_to) as $touser) {
$tousers[] = $touser;
}
$email_to = implode(',', $tousers);

$headers = "From: $mailfrom{$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/html; charset=$charset{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";

if($mailsend == 1 && function_exists('mail')) {

@mail($email_to, $email_subject, $email_message, $headers);

} elseif($mailsend == 2) {

if(!$fp = fsockopen($mailserver, $mailport, $errno, $errstr, 30)) {
die ("SMTP($mailserver:$mailport CONNECT - Unable to connect to the SMTP server");
}
stream_set_blocking($fp, true);

$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != '220') {
die ("SMTP($mailserver:$mailport CONNECT - $lastmessage");
}

fputs($fp, ($mailcfg['auth'] ? 'EHLO' : 'HELO')." SupeSite\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
die ("SMTP($mailserver:$mailport HELO/EHLO - $lastmessage");
}

while(1) {
if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
break;
}
$lastmessage = fgets($fp, 512);
}

if($mailauth) {
fputs($fp, "AUTH LOGIN\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 334) {
die ("SMTP($mailserver:$mailport AUTH LOGIN - $lastmessage");
}

fputs($fp, base64_encode($mailauth_username)."\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 334) {
die ("SMTP($mailserver:$mailport USERNAME - $lastmessage");
}

fputs($fp, base64_encode($mailauth_password)."\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 235) {
die ("SMTP($mailserver:$mailport PASSWORD - $lastmessage");
}

$mailfrom = $mailfrom;
}
fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $mailfrom).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $mailfrom).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
die ("SMTP($mailserver:$mailport  MAIL FROM - $lastmessage");
}
}

foreach(explode(',', $email_to) as $touser) {
$touser = trim($touser);
if($touser) {
fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
$lastmessage = fgets($fp, 512);
die ("SMTP($mailserver:$mailport  RCPT TO - $lastmessage");
}
}
}

fputs($fp, "DATA\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 354) {
die ("SMTP($mailserver:$mailport DATA - $lastmessage");
}

$headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Discuz! Mailer{$maildelimiter}";

fputs($fp, "Date: ".gmdate('r')."\r\n");
fputs($fp, "To: ".$email_to."\r\n");
fputs($fp, "Subject: ".$email_subject."\r\n");
fputs($fp, $headers."\r\n");
fputs($fp, "\r\n\r\n");
fputs($fp, "$email_message\r\n.\r\n");
fputs($fp, "QUIT\r\n");

} elseif($mailsend == 3) {

ini_set('SMTP', $mailserver);
ini_set('smtp_port', $mailport);
ini_set('sendmail_from', $mailfrom);

@mail($email_to, $email_subject, $email_message, $headers);

}
} 

function sendmobile($message) {
 require_once TIPASK_ROOT . '/lib/phpfetion.php';
 // 登陆的手机号、飞信密码（通行证）
 $fetion = new PHPFetion('13482818887', 'gct2008260'); 
 // 接收人手机号、飞信内容	
 $fetion->send('13482818887', $message);
 
}

function complete($subject, $message, $from = '') {
    global $setting;
    $toemail = '1974889570@qq.com';
    $tousername = 'jacky';
    $message = <<<EOT
		Hi, $tousername<br>
            	$subject<br>
            	$message<br><br><br><br>
		这封邮件由系统自动发送，请不要回复。
EOT;
    
     $email_to = $toemail.',panwenjie1227@hotmail.com';   //email地址,多个地址用,分隔开
     $email_subject = $subject;//email标题
     $email_message = $message;//邮件内容
     $charset = 'UTF-8';//邮件编码
     $mailconf = array(
        'mailsend'=>'2',
        'mailserver'=>'smtp.qq.com',
        'mailport'=>'25',
        'mailauth'=>'1',
        'mailfrom'=>'admin@kuaiwd.com',
        'mailauth_username'=>'admin@kuaiwd.com',
        'mailauth_password'=>'qin1234',
        'maildelimiter'=>'0',
        'mailsilent'=>'0',
     );
   sharpng_sendmail($email_to, $email_subject, $email_message, $charset, $mailconf);    
}

/* 取得一个字符串的拼音表示形式 */

function getpinyin($str, $ishead=0, $isclose=1) {
    if (!function_exists('gbk_to_pinyin')) {
        require_once(TIPASK_ROOT . '/lib/iconv.func.php');
    }
    if (TIPASK_CHARSET == 'utf-8') {
        $str = utf8_to_gbk($str);
    }
    return gbk_to_pinyin($str, $ishead, $isclose);
}

/* 得到一个分类的getcategorypath，一直到根分类 */

function getcategorypath($cid) {
    global $category;
    $item = $category[$cid];
    $dirpath = $item['dir'];
    while (true) {
        if (0 == $item['pid']) {
            break;
        } else {
            $item = $category[$item['pid']];
        }
        $dirpath = $item['dir'] . '/' . $dirpath;
    }
    return $dirpath;
}

/* 得到问题纯静态的存储路径 */

function getstaticurl($question) {
    global $setting, $category;
    $staticurl = $setting['static_url'];
    $repacearray = array(
        'typedir' => getcategorypath($question['cid']),
        'timestamp' => $question['time'],
        'Y' => date('Y', $question['time']),
        'M' => date('m', $question['time']),
        'D' => date('d', $question['time']),
        'qid' => $question['id'],
        'pinyin' => getpinyin($question['title']) . '_' . $question['id'],
        'py' => getpinyin($question['title'], 1) . '_' . $question['id'],
        'cc' => date('md', $question['time']) . '_' . md5($question['id']),
    );
    foreach ($repacearray as $search => $replace) {
        $staticurl = str_replace($search, $replace, $staticurl);
    }
    return $staticurl;
}

/* 数组类型，是否是向量类型 */

function isVector(&$array) {
    $next = 0;
    foreach ($array as $k => $v) {
        if ($k !== $next)
            return false;
        $next++;
    }
    return true;
}

/* 自己定义tjson_encode */

function tjson_encode($value) {
    switch (gettype($value)) {
        case 'double':
        case 'integer':
            return $value > 0 ? $value : '"' . $value . '"';
        case 'boolean':
            return $value ? 'true' : 'false';
        case 'string':
            return '"' . str_replace(
                            array("\n", "\b", "\t", "\f", "\r"), array('\n', '\b', '\t', '\f', '\r'), addslashes($value)
                    ) . '"';
        case 'NULL':
            return 'null';
        case 'object':
            return '"Object ' . get_class($value) . '"';
        case 'array':
            if (isVector($value)) {
                if (!$value) {
                    return $value;
                }
                foreach ($value as $v) {
                    $result[] = tjson_encode($v);
                }
                return '[' . implode(',', $result) . ']';
            } else {
                $result = '{';
                foreach ($value as $k => $v) {
                    if ($result != '{')
                        $result .= ',';
                    $result .= tjson_encode($k) . ':' . tjson_encode($v);
                }
                return $result . '}';
            }
        default:
            return '"' . addslashes($value) . '"';
    }
}

/* 是否是外部url */

function is_outer($url) {
    $findstr = $domain = $_SERVER["HTTP_HOST"];
    $words = explode('.', $domain);
    if (count($words) > 2) {
        array_shift($words);
        $findstr = implode('.', $words);
    }
    return false === strpos($url, $findstr);
}

/* html中的是否包含外部url */

function has_outer($content) {
    $contain = false;
    if (!function_exists('file_get_html')) {
        require_once(TIPASK_ROOT . '/lib/simple_html_dom.php');
    }
    $html = str_get_html($content);
    $ret = $html->find('a');
    foreach ($ret as $a) {
        if (is_outer($a->href)) {
            $contain = true;
            break;
        }
    }
    $html->clear();
    return $contain;
}

/* 过滤外部url */

function filter_outer($content) {
    if (!function_exists('file_get_html')) {
        require_once(TIPASK_ROOT . '/lib/simple_html_dom.php');
    }
    $html = str_get_html($content);
    $ret = $html->find('a');
    foreach ($ret as $a) {
        if (is_outer($a->href)) {
            $a->outertext = $a->innertext;
        }
    }
    $content = $html->save();
    $html->clear();
    return $content;
}

/* 内存是否够用 */

function is_mem_available($mem) {
    $limit = trim(ini_get('memory_limit'));
    if (empty($limit))
        return true;
    $unit = strtolower(substr($limit, -1));
    switch ($unit) {
        case 'g':
            $limit = substr($limit, 0, -1);
            $limit *= 1024 * 1024 * 1024;
            break;
        case 'm':
            $limit = substr($limit, 0, -1);
            $limit *= 1024 * 1024;
            break;
        case 'k':
            $limit = substr($limit, 0, -1);
            $limit *= 1024;
            break;
    }
    if (function_exists('memory_get_usage')) {
        $used = memory_get_usage();
    }
    if ($used + $mem > $limit) {
        return false;
    }
    return true;
}

//图片处理函数
/* 根据扩展名判断是否图片 */
function isimage($extname) {
    return in_array($extname, array('jpg', 'jpeg', 'png', 'gif', 'bmp'));
}

function image_resize($src, $dst, $width, $height, $crop=0) {
    if (!list($w, $h) = getimagesize($src))
        return "Unsupported picture type!";

    $type = strtolower(substr(strrchr($src, "."), 1));
    if ($type == 'jpeg')
        $type = 'jpg';
    switch ($type) {
        case 'bmp': $img = imagecreatefromwbmp($src);
            break;
        case 'gif': $img = imagecreatefromgif($src);
            break;
        case 'jpg': $img = imagecreatefromjpeg($src);
            break;
        case 'png': $img = imagecreatefrompng($src);
            break;
        default : return false;
    }
// resize
    if ($crop) {
        if ($w < $width or $h < $height) {
            rename($src, $dst);
            return true;
        }
        $ratio = max($width / $w, $height / $h);
        $h = $height / $ratio;
        $x = ($w - $width / $ratio) / 2;
        $w = $width / $ratio;
    } else {
        if ($w < $width and $h < $height) {
            rename($src, $dst);
            return true;
        }
        $ratio = min($width / $w, $height / $h);
        $width = $w * $ratio;
        $height = $h * $ratio;
        $x = 0;
    }
    $new = imagecreatetruecolor($width, $height);
// preserve transparency
    if ($type == "gif" or $type == "png") {
        imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
        imagealphablending($new, false);
        imagesavealpha($new, true);
    }

    imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

    switch ($type) {
        case 'bmp': imagewbmp($new, $dst);
            break;
        case 'gif': imagegif($new, $dst);
            break;
        case 'jpg': imagejpeg($new, $dst);
            break;
        case 'png': imagepng($new, $dst);
            break;
    }
    return true;
}

function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale) {
    list($imagewidth, $imageheight, $imageType) = getimagesize($image);
    $thumb_image_name = TIPASK_ROOT . $thumb_image_name;
    $imageType = image_type_to_mime_type($imageType);
    $newImageWidth = ceil($width * $scale);
    $newImageHeight = ceil($height * $scale);
    $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
    switch ($imageType) {
        case "image/gif":
            $source = imagecreatefromgif($image);
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            $source = imagecreatefromjpeg($image);
            break;
        case "image/png":
        case "image/x-png":
            $source = imagecreatefrompng($image);
            break;
    }
    imagecopyresampled($newImage, $source, 0, 0, $start_width, $start_height, $newImageWidth, $newImageHeight, $width, $height);
    switch ($imageType) {
        case "image/gif":
            imagegif($newImage, $thumb_image_name);
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            imagejpeg($newImage, $thumb_image_name);
            break;
        case "image/png":
        case "image/x-png":
            imagepng($newImage, $thumb_image_name);
            break;
    }
    chmod($thumb_image_name, 0777);
    return $thumb_image_name;
}

/**
 * 获取内容中的第一张图
 * @param unknown_type $string
 * @return unknown|string
 */
function getfirstimg(&$string) {
    preg_match("/<img.+?src=[\\\\]?\"(.+?)[\\\\]?\"/i", $string, $imgs);
    if (isset($imgs[1])) {
        return $imgs[1];
    } else {
        return "";
    }
}

function highlight($content, $words, $highlightcolor='red') {
    $wordlist = explode(" ", $words);
    foreach ($wordlist as $hightlightword) {
        if (strlen($content) < 1 || strlen($hightlightword) < 1) {
            return $content;
        }
        $content = preg_replace("/$hightlightword/is", "<font color=red>\\0</font>;", $content);
    }
    return $content;
}

function do_post($url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, $url);
    $ret = curl_exec($ch);

    curl_close($ch);
    return $ret;
}

function get_url_contents($url) {
    if (ini_get("allow_url_fopen") == "1")
        return file_get_contents($url);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

function get_remote_image($url, $savepath) {
    ob_start();
    readfile($url);
    $img = ob_get_contents();
    ob_end_clean();
    $size = strlen($img);
    $fp2 = @fopen(TIPASK_ROOT . $savepath, "a");
    fwrite($fp2, $img);
    fclose($fp2);
    return $savepath;
}

function HmacMd5($data,$key,$lang='utf-8')
{
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// Hacked by Lance Rushing(NOTE: Hacked means written)

//需要配置环境支持iconv，否则中文参数不能正常处理
 if($GLOBALS['cfg_soft_lang'] != 'utf-8' || $lang!='utf-8'){
                if(!function_exists('iconv')){
                        exit('Not install iconv lib!');
                }else{
                        //$key = iconv("GB2312","UTF-8//IGNORE",$key);
                        //$data = iconv("GB2312","UTF-8//IGNORE",$data);
                     }
 }
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;

return md5($k_opad . pack("H*",md5($k_ipad . $data)));
}


//签名函数生成签名串
function getReqHmacString($p2_Order,$p3_Amt,$p4_Cur,$p5_Pid,$p6_Pcat,$p7_Pdesc,$p8_Url,$pa_MP,$pd_FrpId,$pr_NeedResponse)
{
  // 业务类型
  //支付请求，固定值"Buy" .	
  $p0_Cmd = "Buy";
		
  //	送货地址
  // 为"1": 需要用户将送货地址留在易宝支付系统;为"0": 不需要，默认为 "0".
  $p9_SAF = "0";
  $yeepay_config = include TIPASK_ROOT . '/data/yeepay.config.php';  
  $p1_MerId = trim($yeepay_config['yeepayuser']);
  $merchantKey = trim($yeepay_config['yeepaykey']);

  #进行签名处理，一定按照文档中标明的签名顺序进行
  $sbOld = "";
  #加入业务类型
  $sbOld = $sbOld.$p0_Cmd;
  #加入商户编号
  $sbOld = $sbOld.$p1_MerId;
  #加入商户订单号
  $sbOld = $sbOld.$p2_Order;     
  #加入支付金额
  $sbOld = $sbOld.$p3_Amt;
  #加入交易币种
  $sbOld = $sbOld.$p4_Cur;
  #加入商品名称
  $sbOld = $sbOld.$p5_Pid;
  #加入商品分类
  $sbOld = $sbOld.$p6_Pcat;
  #加入商品描述
  $sbOld = $sbOld.$p7_Pdesc;
  #加入商户接收支付成功数据的地址
  $sbOld = $sbOld.$p8_Url;
  #加入送货地址标识
  $sbOld = $sbOld.$p9_SAF;
  #加入商户扩展信息
  $sbOld = $sbOld.$pa_MP;
  #加入银行编码
  $sbOld = $sbOld.$pd_FrpId;
  #加入是否需要应答机制
  $sbOld = $sbOld.$pr_NeedResponse;
  return HmacMd5($sbOld,$merchantKey,'GB2312');
  
} 

function getCallbackHmacString($r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType)
{  

    $yeepay_config = include TIPASK_ROOT . '/data/yeepay.config.php';  
	$p1_MerId = trim($yeepay_config['yeepayuser']);
	$merchantKey = trim($yeepay_config['yeepaykey']);


	#取得加密前的字符串
	$sbOld = "";
	#加入商家ID
	$sbOld = $sbOld.$p1_MerId;
	#加入消息类型
	$sbOld = $sbOld.$r0_Cmd;
	#加入业务返回码
	$sbOld = $sbOld.$r1_Code;
	#加入交易ID
	$sbOld = $sbOld.$r2_TrxId;
	#加入交易金额
	$sbOld = $sbOld.$r3_Amt;
	#加入货币单位
	$sbOld = $sbOld.$r4_Cur;
	#加入产品Id
	$sbOld = $sbOld.$r5_Pid;
	#加入订单ID
	$sbOld = $sbOld.$r6_Order;
	#加入用户ID
	$sbOld = $sbOld.$r7_Uid;
	#加入商家扩展信息
	$sbOld = $sbOld.$r8_MP;
	#加入交易结果返回类型
	$sbOld = $sbOld.$r9_BType;

	return HmacMd5($sbOld,$merchantKey,'GB2312');

}


#取得返回串中的所有参数
function getCallBackValue(&$r0_Cmd,&$r1_Code,&$r2_TrxId,&$r3_Amt,&$r4_Cur,&$r5_Pid,&$r6_Order,&$r7_Uid,&$r8_MP,&$r9_BType,&$hmac)
{  
	$r0_Cmd		= $_REQUEST['r0_Cmd'];
	$r1_Code	= $_REQUEST['r1_Code'];
	$r2_TrxId	= $_REQUEST['r2_TrxId'];
	$r3_Amt		= $_REQUEST['r3_Amt'];
	$r4_Cur		= $_REQUEST['r4_Cur'];
	$r5_Pid		= $_REQUEST['r5_Pid'];
	$r6_Order	= $_REQUEST['r6_Order'];
	$r7_Uid		= $_REQUEST['r7_Uid'];
	$r8_MP		= $_REQUEST['r8_MP'];
	$r9_BType	= $_REQUEST['r9_BType']; 
	$hmac		= $_REQUEST['hmac'];
	
	return null;
}

function CheckHmac($r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType,$hmac)
{
	if($hmac==getCallbackHmacString($r0_Cmd,$r1_Code,$r2_TrxId,$r3_Amt,$r4_Cur,$r5_Pid,$r6_Order,$r7_Uid,$r8_MP,$r9_BType))
		return true;
	else
		return false;
}

?>